//
//  WebViewController.m
//  XZOA
//
//  Created by yinda on 2018/1/18.
//  Copyright © 2018年 projects. All rights reserved.
//

#import "WebViewController.h"
#import "PDRCoreAppManager.h"
#import "PDRCoreAppFrame.h"
#import "MBProgressHUD.h"

@interface WebViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) PDRCoreAppFrame *appFrame;
@property (nonatomic, assign)int isFirst;
@end

@implementation WebViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self cleanCacheAndCookie];
    [self getSeverURL];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isFirst = 0;
     [self lauchWebview:nil];
    
//    NSString *url = [[NSUserDefaults standardUserDefaults]objectForKey:@"resultUrl"];
//    if (url!=nil) {
//        [self lauchWebview:url];
//    }
    // Do any additional setup after loading the view.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)notifyAction:(NSNotification *)notify {
    NSLog(@"LOAD END!");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:PDRCoreAppDidLoadNotificationKey object:nil];
    [MBProgressHUD hideHUDForView:self.appFrame animated:YES];
    //    [[BDHUD sharedManager] dismissHUD];
}

/**清除缓存和cookie*/
- (void)cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

- (void)lauchWebview:(NSString *)url{
//    self.navigationItem.title = @"H5test";
    
    // 设置状态栏颜色
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = [UIColor whiteColor];
    }
    self.navigationController.navigationBar.hidden = YES;

    UIWebView *webview = [[UIWebView alloc]init];
    CGRect StRect = CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20);
    webview.frame = StRect;
    webview.scalesPageToFit  = YES;
    webview.delegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [webview loadRequest:request];
    [self.view addSubview:webview];
}
#pragma mark- 从特定服务器获取新的服务器地址
- (NSURLSessionTask *)getSeverURL {
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *URL;
//        URL = [NSURL URLWithString:@"http://db.yinda.com.ph/server_oa.txt"];
     URL = [NSURL URLWithString:@"http://218.77.106.72:157/oa_url.txt"];
        // 通过URL初始化task,在block内部可以直接对返回的数据进行处理
        NSURLSessionTask *task = [session dataTaskWithURL:URL
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError* error) {
                
                                            if (!error) {
                                                NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                NSLog(@"请求到的地址%@",dataString);
                                                dispatch_sync(dispatch_get_main_queue(), ^{
                                                     [self lauchWebview:dataString];
                                                });
                                            }
                                            // 请求失败设置默认的地址
                                            
                                            else {
                                                dispatch_sync(dispatch_get_main_queue(), ^{
                                                    [self lauchWebview:@"http://118.249.86.65:157/BodenOA/m/login.php"];
                                                });
                                            }
                                        }];
        // 启动任务
        [task resume];
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [task cancel];
//        });
    
        return task;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    [MBProgressHUD hideHUDForView:self.appFrame animated:YES];
    NSLog(@"%@",request);
    //1.截取到当前地址
    NSURL *url1=request.URL;
    if ([url1.absoluteString containsString:@"data/uploadfile"]&&![url1.absoluteString containsString:@"template/default"]&&![url1.absoluteString containsString:@"PNG"]) {
        NSLog(@"%@",url1.absoluteString);
        if (self.isFirst==1) {
            NSURL *cleanURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url1]];
            [[UIApplication sharedApplication] openURL:cleanURL];
            return NO;
        }
        self.isFirst = 1;
        return YES;
    }
    else if([url1.absoluteString containsString:@"index.php"]){
        self.isFirst = 0;
    }
    else if ([url1.absoluteString containsString:@"data/uploadfile"]&&([url1.absoluteString containsString:@"PNG"]||[url1.absoluteString containsString:@"png"]||[url1.absoluteString containsString:@"jpg"]||[url1.absoluteString containsString:@"jpeg"]||[url1.absoluteString containsString:@"JPG"]||[url1.absoluteString containsString:@"JPEG"])){
        NSLog(@"%@",url1.absoluteString);
        if (self.isFirst==2) {
            NSURL *cleanURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url1]];
            [[UIApplication sharedApplication] openURL:cleanURL];
            return NO;
        }
        self.isFirst = self.isFirst+1;
        if(self.isFirst>=2){
            self.isFirst = 2;
        }
        return YES;
    }
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
